package com.example.springkotlindemo.controller

import com.example.springkotlindemo.entity.MyTest
import com.example.springkotlindemo.model.AjaxResult
import kotlinx.coroutines.Dispatchers.Unconfined
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.mono
import org.slf4j.LoggerFactory
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate
import org.springframework.data.r2dbc.core.allAndAwait
import org.springframework.data.r2dbc.core.applyAndAwait
import org.springframework.data.r2dbc.core.usingAndAwait
import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Query
import org.springframework.data.relational.core.query.Update
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
import java.time.LocalDateTime
import javax.annotation.Resource

/**
 * @author Xu Haidong
 * @date 2023/4/25 9:45
 */
@RestController
@RequestMapping("/myTest")
class MyTestController {

    private val logger = LoggerFactory.getLogger(this.javaClass)

    @Resource
    private lateinit var template: R2dbcEntityTemplate

    @GetMapping("/start")
    fun start(): Mono<AjaxResult> = mono(Unconfined) {
        val test = MyTest()
        test.name = "张三"
        test.createTime = LocalDateTime.now()
        logger.info("开始新增")
        val res = template.insert(MyTest::class.java).into(MyTest.tableName).usingAndAwait(test)
        val id = res.id
        logger.info("开始查询id=$id")
        val queryRes = template.select(MyTest::class.java).from(MyTest.tableName).matching(
            Query.query(Criteria.where("id").`is`(id!!))
        ).one().awaitSingle()
        logger.info("开始修改")
        val update = Update.update("name","李四")
        template.update(MyTest::class.java).inTable(MyTest.tableName).matching(
            Query.query(Criteria.where("id").`is`(id))
        ).applyAndAwait(update)
        logger.info("开始删除")
        template.delete(MyTest::class.java).from(MyTest.tableName).matching(
            Query.query(Criteria.where("id").`is`(id))
        ).allAndAwait()
        AjaxResult.success()
    }
}